package com.liu.yubi.manager;

import com.liu.yubi.common.ErrorCode;
import com.liu.yubi.constant.AIConstant;
import com.liu.yubi.exception.BusinessException;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lqh
 * @since 2025-06-29 23:24
 * 智谱AI管理器
 */
@Component
@Slf4j
public class ZPAIManager {


    @Resource
    private ClientV4 clientV4;

    /**
     * 同步调用
     */
    public String doChat(ChatMessage content) {

        List<ChatMessage> messages = new ArrayList<> ();
        //预设
        String aiPromptTemplate = AIConstant.AI_PROMPT_TEMPLATE;
        ChatMessage prompt = new ChatMessage (ChatMessageRole.USER.value (), aiPromptTemplate);
        messages.add (prompt);
        if (content==null){
            throw new BusinessException (ErrorCode.PARAMS_ERROR,"AI请求参数为空");
        }
        messages.add (content);
        String requestId = String.format ("YourRequestId-%d", System.currentTimeMillis ());
        //指定模型
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder ()
                .model (Constants.ModelChatGLM4)
                .stream (Boolean.FALSE)
                .invokeMethod (Constants.invokeMethod)
                .messages (messages)
                .requestId (requestId)
                .build ();
        ModelApiResponse invokeModelApiResp = clientV4.invokeModelApi (chatCompletionRequest);
        //ai响应结果
        String result =invokeModelApiResp.getData ().getChoices ().get (0).getMessage ().getContent ().toString();
        //打印日志
        log.info ("AI响应结果==>{}",result);
        //返回响应ai处理结果
        return result;

    }
}
